package com.bifrost.service.impl;

import com.bifrost.cbentity.*;
import com.bifrost.cbrepository.*;
import com.bifrost.entity.*;
import com.bifrost.repository.*;
import com.bifrost.service.SapDataSyncService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author rangf
 * @date 2018/2/28
 */
@Service
public class SapDataSyncServiceImpl implements SapDataSyncService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SapDataSyncServiceImpl.class);

    @Autowired
    MerchantStoreRepository merchantStoreRepository;
    @Autowired
    SapStoreRepository sapStoreRepository;
    @Autowired
    SapBrandRepository sapBrandRepository;
    @Autowired
    ProductBrandRepository productBrandRepository;
    @Autowired
    SapProductRepository sapProductRepository;
    @Autowired
    SapGoodsRepository sapGoodsRepository;
    @Autowired
    SapStoreProductRepository sapStoreProductRepository;
    @Autowired
    SapStoreGoodsRepository sapStoreGoodsRepository;
    @Autowired
    SapContractRepository sapContractRepository;
    @Autowired
    SapProtocolRepository sapProtocolRepository;
    @Autowired
    SapContractProductRepository sapContractProductRepository;
    @Autowired
    SapProtocolProductRepository sapProtocolProductRepository;
    @Autowired
    SapPartnerRepository partnerRepository;

    @Override
    //@Transactional(rollbackFor = {Exception.class})
    public void syncSapStore() {
        List<SapStore> sapStoreList = sapStoreRepository.findAllByDstatus("0");
        if (CollectionUtils.isNotEmpty(sapStoreList)) {
            sapStoreList.forEach(sapStore -> {
                if(!"1".equals(sapStore.getDstatus())){
                    MerchantStore store =null;
                    store=  merchantStoreRepository.findFirstByExternalId(sapStore.getKunnr());
                    if(store==null){
                        store = new MerchantStore();
                    }
                    store.setStoreName(sapStore.getName1());
                    store.setStoreAddress(sapStore.getStras());
                    store.setStoreCode(sapStore.getKunnr());
                    store.setStorePhone(sapStore.getTelf1());
                    store.setExternalId(sapStore.getKunnr());
                    store.setAvailable(Boolean.TRUE);
                    merchantStoreRepository.save(store);
                    sapStore.setDstatus("1");
                    sapStoreRepository.save(sapStore);
                }
            });
        }

    }

    @Override
    public void syncSapBrand() {
        List<SapBrand> sapBrandList = sapBrandRepository.findAllByDstatus("0");
        sapBrandList.forEach(sapBrand -> {
            Long brandCode=null;
            try {
                brandCode = Long.valueOf(sapBrand.getPpbm());
                ProductBrand brand = productBrandRepository.findOne(brandCode);
                sapBrand.setDstatus("1");
                if(brand == null){
                    //设置基本属性
                   productBrandRepository.saveSapBrand(brandCode,sapBrand.getPpmcZh());
                   sapBrandRepository.save(sapBrand);
                }else {
                   sapBrandRepository.save(sapBrand);
                }
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.warn("品牌同步错误 编码：{}",brandCode);
            }
        });
    }

    @Override
    public void syncSapGoods() {
       List<SapProduct> products = sapProductRepository.findAllByDstatus("0",new PageRequest(0,1000));
       while (CollectionUtils.isNotEmpty(products)){
           for(SapProduct sapProduct : products){
               try {
                   SapGoods goods=null;
                   goods = sapGoodsRepository.findFirstByMatnr(sapProduct.getMatnr());
                   if(goods == null){
                       goods = new SapGoods();
                   }
                   BeanUtils.copyProperties(sapProduct,goods );
                   sapGoodsRepository.save(goods);
                   //sapProduct = sapProductRepository.findOne(sapProduct.getNoid());
                   sapProduct.setDstatus("1");
                   sapProductRepository.save(sapProduct);
               }catch (Exception e){
                   LOGGER.error(String.format("商品%s:%s同步失败",sapProduct.getMatnr(),sapProduct.getMaktx()),e);
                   continue;
               }
           }
           products = sapProductRepository.findAllByDstatus("0",new PageRequest(0,1000));
       }
        products =null;
    }

    /**
     * 同步门店商品主数据
     */
    @Override
    public void synSapStoreGoods() {
       List<SapStoreProduct> products = sapStoreProductRepository.findAllByDstatus("0",new PageRequest(0,1000));
        while (CollectionUtils.isNotEmpty(products)) {
            for(SapStoreProduct sapStoreProduct :products ){
                try{
                    String matnr =  sapStoreProduct.getMatnr();
                    String store = sapStoreProduct.getLocnr();
                    if (!StringUtils.isAnyEmpty(matnr,store)) {
                        SapStoreGoods goods =null;
                        goods = sapStoreGoodsRepository.findFirstByMatnrAndLocnr(matnr,store);
                        if(goods==null){
                            goods= new SapStoreGoods();
                        }
                        BeanUtils.copyProperties(sapStoreProduct,goods );
                        sapStoreGoodsRepository.save(goods);
                        sapStoreProduct.setDstatus("1");
                        sapStoreProductRepository.save(sapStoreProduct);
                    }
                }catch (Exception e){
                    LOGGER.error(String.format("门店%s商品%s同步失败",sapStoreProduct.getLocnr(),sapStoreProduct.getMatnr()),e);
                    continue;
                }
            }
            products = sapStoreProductRepository.findAllByDstatus("0",new PageRequest(0,1000));
        }
        products=null;
    }

    /**
     * 同步sap合同主数据
     */
    @Override
    public void synSapContract() {
      List<SapContract>  contracts = sapContractRepository.findAllByDstatus("0",new PageRequest(0,1000));
        while (CollectionUtils.isNotEmpty(contracts)) {
            for (SapContract contract : contracts){
                try {
                    SapProtocol protocol =null;
                    protocol =sapProtocolRepository.findFirstByRecnnr(contract.getRecnnr());
                    if (protocol==null) {
                        protocol =new SapProtocol();
                    }
                    BeanUtils.copyProperties(contract,protocol );
                    sapProtocolRepository.save(protocol);
                    contract.setDstatus("1");
                    sapContractRepository.save(contract);
                }catch (Exception e){
                    LOGGER.error(String.format("合同%s同步失败",contract.getRecnnr()),e);
                    continue;
                }
            }
            contracts = sapContractRepository.findAllByDstatus("0",new PageRequest(0,1000));
        }
        contracts=null;
    }

    /**
     * 同步sap合同和商品关系数据
     */
    @Override
    public void synSapContractGoods() {
    List<SapContractProduct> contractProducts =sapContractProductRepository.findAllByDstatus("0",new PageRequest(0,1000));
        while (CollectionUtils.isNotEmpty(contractProducts)) {
            for (SapContractProduct contractProduct : contractProducts){
                try {
                    SapProtocolProduct protocolProduct = null;
                    protocolProduct = sapProtocolProductRepository.findFirstByMatnrAndWerks(contractProduct.getMatnr(),contractProduct.getWerks());
                    if (protocolProduct==null) {
                        protocolProduct =new SapProtocolProduct();
                    }
                    BeanUtils.copyProperties(contractProduct,protocolProduct );
                    sapProtocolProductRepository.save(protocolProduct);
                    contractProduct.setDstatus("1");
                    sapContractProductRepository.save(contractProduct);
                }catch (Exception e){
                    LOGGER.error(String.format("商品%s门店%s柜号同步失败",contractProduct.getMatnr(),contractProduct.getWerks()),e);
                    continue;
                }
            }
            contractProducts =sapContractProductRepository.findAllByDstatus("0",new PageRequest(0,1000));
        }
        contractProducts=null;
    }
}
